//
//  SYDetailViewController.m
//  BSHOUYIFANG
//
//  Created by lanou on 15/8/16.
//  Copyright (c) 2015年 CYB. All rights reserved.
//

#import "SYDetailViewController.h"
#import "Header.h"
#import "SYMomentsFirstTableViewController.h"
#import "NSString+Html.h"
#import "FMDatabase.h"
#import "FMResultSet.h"
#import "SYFileHandle.h"
#import "SYMomentsFirstModel.h"
#import "MYRequestManger.h"
#import "SYFileHandle.h"
#import "SYLoginViewController.h"
@interface SYDetailViewController ()<UIWebViewDelegate>
@property (nonatomic,strong)FMDatabase *db;
@property (nonatomic,strong)UIView *lineView;
@property (nonatomic,strong)NSString *backupStr;

@end

@implementation SYDetailViewController
- (void)findForArrayWithID
{
    if (!_myID) {
        return;
    }
    NSLog(@"%@ %@ %@",_myID,_backupImg,_backupTitle);
    _urlStr = [NSString stringWithFormat:@"http://sdxapp.com/quan.html?act=post&sayid=%@&mqid=556",_myID];
    if (!_myBool) {
        _urlStr = [NSString stringWithFormat:@"http://sdxapp.com/quan.html?act=post&sayid=%@&mqid=556",_myID];
        _bottomView.backButton.tag = 2001;
    }else
    {
        _urlStr = [NSString stringWithFormat:@"http://sdxapp.com/quan.html?act=post&sayid=%@&mqid=556",_myID];
        _bottomView.backButton.tag = 2002;
        _myBool = NO;
    }
    //_myID = 0;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    _detailView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20)];
    _detailView.backgroundColor = [UIColor whiteColor];
    _detailView.delegate = self;
    _detailView.scalesPageToFit = YES;
    [self.view addSubview:_detailView];
    
    //*************创建数据库/通知中心*************//
    
   
    NSString *str = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filrPath = [str stringByAppendingPathComponent:@"like.db"];
    _db = [FMDatabase databaseWithPath:filrPath];
    if (![_db open]) {
        NSLog(@"%@",filrPath);
    }
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [_db executeUpdate:@"create table like (urlstr text, backuptitle text, backupimg text, username text)"];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(cancelLike) name:@"cancelLike" object:nil];
    });
    
    
    //*************底部view与button*************//
    

    _bottomView = [[SYMomentsDetailView alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 50, SCREEN_WIDTH, 50)];
    [_bottomView.backButton setBackgroundImage:[UIImage imageNamed:@"detail_back@3x"] forState:UIControlStateNormal];
    _bottomView.backgroundColor = [UIColor whiteColor];
    [self findForArrayWithID];
    if ([self islike]) {
        [_bottomView.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_red@3x"] forState:UIControlStateNormal];
    }else{
    [_bottomView.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_gray@3x"] forState:UIControlStateNormal];
    }
    
    _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.3)];
    _lineView.backgroundColor = [UIColor grayColor];
    [_bottomView addSubview:_lineView];
    [_bottomView.backButton addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView.likeButton addTarget:self action:@selector(doLike:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomView];
   
    
    //*************webview数据处理*************//
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //截取需要的字符串
        NSString *str = [NSString stringWithContentsOfURL:[NSURL URLWithString:_urlStr] encoding:NSUTF8StringEncoding error:nil];
        NSString *temp = @"<div class=\"info-list\">";
        NSRange range = [str rangeOfString:temp];
        
        NSString *temp2 = @"<!-- /ft -->";
        NSRange range2 = [str rangeOfString:temp2];
        
        NSMutableString *s = [str mutableCopy];
        [s deleteCharactersInRange:NSMakeRange(range.location, range2.location + range2.length - range.location)];
        
        NSString *temp3 = @"<body data-page-name=\"show\">";
        NSRange range3 = [s rangeOfString:temp3];
        NSString *temp4 = @"</div><!-- /hd -->";
        NSRange range4 = [s rangeOfString:temp4];
        
        [s deleteCharactersInRange:NSMakeRange(range3.location + 5, range4.location + range4.length - range3.location)];
        _backupStr = s;
        //图片自适应宽度
        NSString *widthStr = [NSString stringWithFormat:@"t%.0f",SCREEN_WIDTH - 16];
        NSString *temp5 = @"t600";
        NSRange range5 = NSMakeRange(0, 1);
        do {
            range5 = [s rangeOfString:temp5];
            if (range5.length != 0) {
                [s replaceCharactersInRange:range5 withString:widthStr];
                NSString *count = [s substringWithRange:NSMakeRange(range5.location + range5.length + 1, 3)];
                CGFloat height = [count floatValue];
                CGFloat h = height * 359 / 600;
                NSString *hh = [NSString stringWithFormat:@"%.0f",h];
                [s replaceCharactersInRange:NSMakeRange(range5.location + range5.length + 1, 3) withString:hh];
            }
        } while (range5.length);
        
        //webview加载字符串
        [_detailView loadHTMLString:s baseURL:nil];
    });

}

   //*************取消收藏状态*************//

- (void)cancelLike{
    [_bottomView.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_gray@3x"] forState:UIControlStateNormal];
}


- (void)webViewDidFinishLoad:(UIWebView *)webView{
    _detailView.frame = CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 70);
}


   //*************返回点击事件*************//

- (void)doBack:(UIButton *)sender{
    if (_jumpIndex == 1) {
        NSArray *arr = [self.navigationController viewControllers];
        NSLog(@"%@",arr[2]);
        [self.navigationController popToViewController:arr[2] animated:YES];
        return;
    }
    if(sender.tag == 2001)
    {
        [self.navigationController popToRootViewControllerAnimated:YES];
        sender.tag = 2002;
    }else{
    NSArray *arr = [self.navigationController viewControllers];
    [self.navigationController popToViewController:arr[1] animated:YES];
    }
}


  //*************收藏点击事件*************//

- (void)doLike:(UIButton *)sender{
    BOOL islogin = [[SYFileHandle shareInstance] loginState];
    if (!islogin) {
        SYLoginViewController *loginVC = [[SYLoginViewController alloc]init];
        __weak SYLoginViewController *tempVC = loginVC;
        loginVC.loginAppear = ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [tempVC.longinView endEditing:YES];
            });
            dispatch_async(dispatch_get_main_queue(), ^{
                [tempVC dismissViewControllerAnimated:YES completion:nil];
            });
        };
        [self presentViewController:loginVC animated:YES completion:nil];
        return;
    }
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
    NSString *userName = [[SYFileHandle shareInstance] phoneNumber];
    FMResultSet *result = [_db executeQuery:@"select urlstr, backuptitle from like where username = ?",userName];
    while ([result next]) {
        NSString *title = [result stringForColumn:@"urlstr"];
        if (title.length ==0) {
            break;
        }
        [arr addObject:title];
    }
    //第一次收藏
    if (arr.count == 0) {
        [_db executeUpdate:@"insert into like (urlstr,backuptitle,backupimg,username) values (?,?,?,?)",self.urlStr,self.backupTitle,self.backupImg,userName];
        [_bottomView.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_red@3x"] forState:UIControlStateNormal];
        return;
    }
    //如果已收藏
    for (NSString *urlstr in arr) {
        if ([urlstr isEqualToString:self.urlStr]) {
            [_db executeUpdate:@"delete from like where urlstr = ? and username = ?",self.urlStr,userName];
            [_bottomView.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_gray@3x"] forState:UIControlStateNormal];
            return;
        }
    }
    //如果还没收藏
    [_db executeUpdate:@"insert into like (urlstr,backuptitle,backupimg,username) values (?,?,?,?)",self.urlStr,self.backupTitle,self.backupImg,userName];
    [_bottomView.likeButton setBackgroundImage:[UIImage imageNamed:@"detail_like_red@3x"] forState:UIControlStateNormal];
    [result close];
}



- (BOOL)islike{
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:0];
        NSString *userName = [[SYFileHandle shareInstance] phoneNumber];
        FMResultSet *result = [_db executeQuery:@"select urlstr from like where username = ?",userName];
        while ([result next]) {
            NSString *title = [result stringForColumn:@"urlstr"];
            if (title.length ==0) {
                break;
            }
            [arr addObject:title];
        }
        if (arr.count == 0) {
            return 0;
        }
        for (NSString *urlstr in arr) {
            if (![urlstr isEqualToString:self.urlStr]) {
                continue;
            }else{
                return 1;
            }
        }
        [result close];
    return 0;
}




- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    //self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.hidden = YES;
}


-(void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
